package models

import (
	"fmt"
	"reflect"
	"strings"
	"time"

	"gitee.com/lzqysoft/ims/libs/encrypt"

	"github.com/astaxie/beego/orm"
	"github.com/pkg/errors"
)

// Implement 项目实施记录详情
type ImplementDetail struct {
	Id            string    `orm:"column(id);pk"`
	Alisa         string    `orm:"column(alisa)"`
	ImplementId   string    `orm:"column(implement_id)"`
	ProdId        string    `orm:"column(prod_id)"`
	ProdName      string    `orm:"column(prod_name)"`
	OrderId       string    `orm:"column(order_id);null"`
	OrderName     string    `orm:"column(order_name);null"`
	PUID          string    `orm:"column(puid)"`
	Account       string    `orm:"column(account)"`
	SetTime       time.Time `orm:"column(set_time)"`
	Seter         string    `orm:"column(seter)"`
	InstallResult int       `orm:"column(install_result)"` // 0. 未调试，1. 已调试，未安装 2.已安装 3.其它
	InstallRemark string    `orm:"column(install_remark)"`
	Installer     string    `orm:"column(installer)"`
	InstallTime   time.Time `orm:"column(install_time)"`
	Contact       string    `orm:"column(contact)"`
	Phone         string    `orm:"column(phone)"`
	Address       string    `orm:"column(address)"`
	Remark        string    `orm:"column(remark);null"`
	Status        int       `orm:"column(status)"`
	Isdelete      int       `orm:"column(isdelete)"`
	Ctime         time.Time `orm:"column(ctime);type(timestamp with time zone)"`
	Creater       string    `orm:"column(creater);null"`
	Utime         time.Time `orm:"column(utime);type(timestamp with time zone)"`
	Updater       string    `orm:"column(updater);null"`
}

func (t *ImplementDetail) TableName() string {
	return "yjk_implement_detail"
}

func init() {
	orm.RegisterModel(new(ImplementDetail))
}

func AddImplementFromImplementAndProdsAndUserAndOuts(order *Order, imp *Implement, prods []Prod, user *User, outs []Outs) (int, error) {
	items := []ImplementDetail{}
	for _, out := range outs {
		for i := 0; i < out.Count; i++ {
			item := ImplementDetail{}
			prod, err := checkProd(prods, out.ProdId)
			if err != nil {
				return 0, err
			}
			item.Id = encrypt.GetGuid()
			item.ImplementId = imp.Id
			item.Alisa = prod.Name
			item.ProdId = prod.Id
			item.ProdName = prod.Name
			item.OrderName = order.Name
			item.OrderId = order.Id
			item.InstallResult = 0
			item.Status, item.Isdelete, item.Ctime, item.Creater, item.Utime, item.Updater =
				1, 0, time.Now(), order.Creater, time.Now(), user.Abbr
			items = append(items, item)
		}
	}
	if len(items) > 0 {
		o := orm.NewOrm()
		nums, err := o.InsertMulti(len(items), items)
		if err != nil {
			return 0, err
		}
		return int(nums), nil
	}

	return 0, errors.New("none data list")
}

func checkProd(prods []Prod, id string) (Prod, error) {
	for _, v := range prods {
		if v.Id == id {
			return v, nil
		}
	}
	return Prod{}, errors.New("recode not found!")
}

func GetImplementsByImplementId(implementId string) ([]ImplementDetail, error) {
	o := orm.NewOrm()
	var items []ImplementDetail
	_, err := o.QueryTable(new(ImplementDetail)).Filter("Isdelete", 0).Filter("ImplementId", implementId).OrderBy("-Utime").
		All(&items)
	return items, err
}

func UpdateImplementDetail(m *ImplementDetail) (err error) {
	o := orm.NewOrm()
	v := ImplementDetail{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

func GetImplementDetailById(id string) (v *ImplementDetail, err error) {
	o := orm.NewOrm()
	v = &ImplementDetail{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

func GetAllImplements(query map[string]string, fields []string, sortby []string, order []string,
	offset int64, limit int64) (ml []interface{}, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(ImplementDetail))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	qs = qs.Filter("Isdelete", 0)
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, errors.New("Error: unused 'order' fields")
		}
	}

	var l []ImplementDetail
	qs = qs.OrderBy(sortFields...)
	if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
		if len(fields) == 0 {
			for _, v := range l {
				s := make(map[string]interface{})
				ve := reflect.ValueOf(v)
				t := reflect.TypeOf(v)
				for i := 0; i < t.NumField(); i++ {
					//					beego.Debug(t.Field(i).Name, ve.Field(i).Interface())
					s[t.Field(i).Name] = ve.Field(i).Interface()
				}
				ml = append(ml, s)
			}
		} else {
			// trim unused fields
			for _, v := range l {
				m := make(map[string]interface{})
				val := reflect.ValueOf(v)
				for _, fname := range fields {
					m[fname] = val.FieldByName(fname).Interface()
				}
				ml = append(ml, m)
			}
		}
		return ml, nil
	}
	return nil, err
}


func GetImplementDetailsCountByImplementId(id string) (int64,error) {
	o := orm.NewOrm()
	count, err :=o.QueryTable(new(ImplementDetail)).Filter("Isdelete",0).Filter("ImplementId",id).Count()
	return count, err
}